<template>
  <je-tabs v-model:activeKey="templeteActiveKey" class="tab-container">
    <je-tab-pane key="1">
      <template #tab>
        <span>
          <i class="fal fa-rectangles-mixed"></i>
          列表模版
        </span>
      </template>
      <je-collapse v-model:activeKey="activeKeyTemplete" accordion disable-empty-active>
        <je-collapse-panel
          v-for="funcItem in listTemplete"
          :key="funcItem.key"
          :header="funcItem.header"
        >
          <div
            :style="`height: ${collapseHeight}px; overflow-y: scroll;padding: ${
              funcItem.key == 'cunstom' && systemTempleteData.length <= 0 ? 0 : '20px'
            }`"
            class="templete-container"
          >
            <div
              v-for="item in funcItem.key == 'defalut1' ? defaultTempleteData : systemTempleteData"
              :key="item"
              class="templete-item"
              @mouseenter="mouseenterItem(item)"
              @mouseleave="mouseenterKey = ''"
            >
              <img :src="`${getFileUrlByKey(item.fileKey)}`" />
              <div v-if="item.JE_META_APPS_TEMPLETE_ID == mouseenterKey" class="templete-float">
                <div>
                  <div @click.stop="handleImg(item, 'preview')"
                    ><i class="fal fa-magnifying-glass-plus"></i>放大</div
                  >
                  <div style="margin-top: 5px" @click.stop="handleImg(item, 'application')"
                    ><i class="fal fa-check-circle"></i>应用</div
                  >
                </div>
              </div>
            </div>
            <div v-if="funcItem.key == 'cunstom' && systemTempleteData.length <= 0" class="no-data">
              请前往自定义模版维护数据~
            </div>
          </div>
        </je-collapse-panel>
      </je-collapse>
    </je-tab-pane>
    <je-tab-pane key="2">
      <template #tab>
        <span>
          <i class="fal fa-ballot"></i>
          功能字段
        </span>
      </template>
      <je-collapse v-model:activeKey="activeKey" accordion disable-empty-active>
        <je-collapse-panel
          v-for="funcItem in funcField"
          :key="funcItem.key"
          :header="funcItem.header"
        >
          <div
            :style="`height: ${collapseHeight}px; overflow-y: scroll`"
            class="collapse-container"
          >
            <div
              v-for="item in funcItem.key == 'professional'
                ? professionalFieldData
                : systemFieldData"
              :key="item"
              class="filed-item"
            >
              <div class="name">{{ item.RESOURCECOLUMN_NAME }}</div>

              <div class="code"
                ><je-tooltip placement="top" :title="item.RESOURCECOLUMN_CODE">
                  {{ item.RESOURCECOLUMN_CODE }}</je-tooltip
                ></div
              >
            </div>
          </div>
        </je-collapse-panel>
      </je-collapse>
    </je-tab-pane>
  </je-tabs>
</template>

<script>
  import {
    reactive,
    toRefs,
    defineComponent,
    onMounted,
    onBeforeMount,
    watch,
    nextTick,
    h,
  } from 'vue';
  import { Tabs, Collapse, Modal, File, Tooltip, EditorCode } from '@jecloud/ui';
  import { decode, getFileUrlByKey, encode } from '@jecloud/utils';
  import { ListFieldConfigGet, getData } from '@/api/index';

  export default defineComponent({
    name: 'FormFieldConfig',
    components: {
      JeTabs: Tabs,
      JeTabPane: Tabs.pane,
      JeCollapse: Collapse,
      JeCollapsePanel: Collapse.panel,
      JeTooltip: Tooltip,
    },
    props: {
      funcId: String,
      recordData: Object,
      height: Number,
    },
    emits: ['sharedData'],
    setup(props, { emit }) {
      const state = reactive({
        mouseenterKey: '',
        templeteActiveKey: '1',
        templateFlag: true,
        collapseHeight: 0,
        activeKey: 'professional',
        funcId: props.funcId,
        loading: false,
        checkTemplete: { key: 1 },
        professionalFieldData: [],
        systemFieldData: [],
        defaultTempleteData: [],
        activeKeyTemplete: 'defalut1',
        systemTempleteData: [],
        listTemplete: [
          { key: 'defalut1', header: '官方模版' },
          {
            key: 'cunstom',
            header: '自定义模版',
          },
        ],
        funcField: [
          { key: 'professional', header: '业务字段' },
          {
            key: 'system',
            header: '系统字段',
          },
        ],
        getFileUrlByKey,
      });

      const methods = {
        // 点击放大和应用图片
        handleImg(item, type) {
          if (type == 'preview') {
            Modal.window({
              title: '列表配置',
              content: () =>
                h(
                  'div',
                  { style: { display: 'flex', width: '100%', height: '100%', overflow: 'hidden' } },
                  [
                    h('img', {
                      style: {
                        height: '100%',
                        // border: '1px solid #d9d9d9',
                      },
                      src: `${getFileUrlByKey(item.fileKey)}`,
                    }),
                    h(EditorCode, {
                      value: item.TEMPLETE_FFT,
                      readonly: true,
                      hideApi: true,
                      style: {
                        height: '100%',
                      },
                    }),
                  ],
                ),
            });
            // File.previewFile(decode(item.TEMPLETE_MBXGT)[0]);
          } else {
            // 应用
            Modal.confirm('该操作会覆盖原有的列表样式配置，请谨慎操作！', () => {
              methods.clickTempleteItem(item);
            });
          }
        },
        // 点击官方模版
        clickTempleteItem(item) {
          state.checkTemplete = item;
          emit('sharedData', state.checkTemplete);
        },
        getListFields() {
          state.professionalFieldData = [];
          state.systemFieldData = [];
          state.loading = true;
          const params = {
            tableCode: 'JE_CORE_RESOURCECOLUMN',
            funcId: state.funcId,
            j_query: JSON.stringify({
              custom: [
                { code: 'RESOURCECOLUMN_FUNCINFO_ID', value: state.funcId, type: '=' },
                {
                  code: 'RESOURCECOLUMN_XTYPE',
                  value: ['rownumberer', 'actioncolumn'],
                  type: 'notIn',
                  cn: 'and',
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
          };

          ListFieldConfigGet(params)
            .then((res) => {
              state.loading = false;
              if (res.success && res.data.rows.length) {
                const { rows } = res.data;
                rows.map((item) => {
                  const { RESOURCECOLUMN_NAME, RESOURCECOLUMN_CODE } = item;
                  const obj = {
                    RESOURCECOLUMN_NAME,
                    RESOURCECOLUMN_CODE,
                  };
                  //说明是系统字段
                  if (RESOURCECOLUMN_CODE.substring(0, 3) == 'SY_') {
                    state.systemFieldData.push(obj);
                  } else {
                    state.professionalFieldData.push(obj);
                  }
                });
              }
            })
            .catch((error) => {
              state.loading = false;
              Modal.alert(error.message, 'error');
            });
        },
        getListTempleteData() {
          state.defaultTempleteData = [];
          state.systemTempleteData = [];
          const params = {
            tableCode: 'JE_META_APPS_LIST_TEMPLETE',
            // funcCode: 'JE_META_APPS_LIST_TEMPLETE',
            j_query: encode({
              custom: [
                {
                  code: 'TEMPLETE_SFQY',
                  type: '=',
                  value: '1',
                },
              ],
            }),
          };
          getData(params).then((res) => {
            res.map((item) => {
              item.fileKey = decode(item.TEMPLETE_MBXGT)[0].fileKey;
              if (item.TEMPLETE_SFGFMB == '1') {
                state.defaultTempleteData.push(item);
              } else {
                state.systemTempleteData.push(item);
              }
              methods.showJsRow();
            });
          });
        },
        // 鼠标移入，获取激活的key
        mouseenterItem(item) {
          state.mouseenterKey = item.JE_META_APPS_TEMPLETE_ID;
        },
        // 回显编辑器里面内容
        showJsRow() {
          const gridJsData = props.recordData.FUNCINFO_GRIDJSLISTENER
            ? decode(props.recordData.FUNCINFO_GRIDJSLISTENER)
            : [];
          const ishasAppRowRenderer = gridJsData.filter((item) => item.code == 'row-renderer');
          if (ishasAppRowRenderer && ishasAppRowRenderer.length && ishasAppRowRenderer[0].func) {
            methods.clickTempleteItem({ TEMPLETE_FFT: ishasAppRowRenderer[0].func });
          } else {
            // 获取数据为空
            // const j_query = {
            //   order: [
            //     { type: 'asc', code: 'VIEWEVENTS_TYPE' },
            //     { type: 'asc', code: 'SY_ORDERINDEX' },
            //   ],
            //   custom: [
            //     {
            //       code: 'VIEWEVENTS_JY',
            //       type: '!=',
            //       value: '1',
            //     },
            //   ],
            // };
            // getData({
            //   tableCode: 'JE_CORE_VIEWEVENTS',
            //   limit: -1,
            //   j_query: JSON.stringify(j_query),
            // }).then((data) => {
            //   const rowRenderData = data.find((item) => item.VIEWEVENTS_CODE == 'row-renderer');
            //   methods.clickTempleteItem({ TEMPLETE_FFT: rowRenderData.VIEWEVENTS_FUNC });
            // });
            const templeteDatalist = state.defaultTempleteData.find(
              (item) => item.TEMPLETE_SFMRMB == '1',
            );
            methods.clickTempleteItem(templeteDatalist);
          }
        },
      };
      onBeforeMount(() => {
        // 获取列表配置模版的数据
        methods.getListTempleteData();
      });
      watch(
        // 切换tabs,获取一次字段配置的数据
        () => state.templeteActiveKey,
        () => {
          if (state.templeteActiveKey == '2' && state.templateFlag) {
            state.templateFlag = false;
            // 获取列表字段
            methods.getListFields();
          }
        },
        { deep: true },
      );

      onMounted(() => {
        // state.collapseHeight = props.height - 38 * 2 - 71;
      });
      watch(
        () => props.height,
        () => {
          nextTick(() => {
            props.height && (state.collapseHeight = props.height - 38 * 2 - 71);
          });
        },
        { deep: true, immediate: true },
      );
      return { ...methods, ...toRefs(state) };
    },
  });
</script>
<style lang="less">
  .tab-container {
    .ant-collapse > .ant-collapse-item > .ant-collapse-header {
      padding: 8px 16px;
      font-size: 14px;
      background: #f7f9fc !important;
    }
    .ant-tabs-nav {
      padding: 0 10px !important;
      margin-bottom: 0px !important;
      border-top: 1px solid #d9d9d9;
      border-right: 1px solid #d9d9d9;
    }
    .ant-collapse-content > .ant-collapse-content-box {
      padding: 0;
    }
    .collapse-container {
      overflow-y: auto;
      &::-webkit-scrollbar {
        width: 0px !important;
      }
    }
  }
</style>
<style lang="less" scoped>
  .tab-container {
    .templete-container {
      .no-data {
        display: flex;
        height: 100%;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        background: #f2f2f2;
      }

      .templete-item {
        display: inline-block;
        margin-bottom: 20px;
        position: relative;
        img {
          // width: 40%;
          width: 146px;
          // height: 220px;
        }
        .templete-float {
          position: absolute;
          z-index: 10;
          background: rgba(0, 0, 0, 0.6);
          width: 100%;
          height: 100%;
          top: 0;
          color: #fff;
          display: flex;
          cursor: pointer;
          align-items: center;
          justify-content: center;
          i {
            margin-right: 8px;
          }
        }
      }
      .templete-item:nth-of-type(2n) {
        margin-left: 20px;
      }
    }

    .filed-item {
      display: flex;
      justify-content: space-between;
      div {
        width: 60%;
        height: 32px;
        line-height: 32px;
        padding: 0 10px;
        white-space: nowrap; // 文字不换行
        overflow: hidden; // 超出隐藏
        text-overflow: ellipsis;
      }
      border-bottom: 1px solid #e6e6e6;
      > :nth-child(2n + 1) {
        width: 40%;
        border-right: 1px solid #e6e6e6;
      }
    }
  }
</style>
